package org.example.dbcompare.service.config;

import cn.hutool.core.io.FileUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONWriter;
import org.example.dbcompare.model.context.DataCompareContext;
import org.example.dbcompare.service.CompareUtils;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.logging.Logger;

/**
 * 配置管理器 - 负责从JSON配置文件加载配置信息
 * @author wuyong
 * @date 2025/10/26
 */
public class ConfigManager {
    private static final Logger logger = Logger.getLogger(ConfigManager.class.getName());
    private static final String CONFIG_DIRECTORY = "config/";
    private static final String RESULT_DIRECTORY = "result/";

    /**
     * 保存结果对象到RESULT目录，文件名追加时间后缀（yyyyMMdd_HHmmss）
     * @param result 结果对象
     */
    public static void saveResult(String result, String fullPath) {
        FileUtil.writeUtf8String(result, fullPath);
    }

    /**
     * 通用保存JSON到资源目录
     * @param obj 待保存对象
     * @param directory 目标子目录（如 CONFIG_DIRECTORY / RESULT_DIRECTORY）
     * @param fileName 文件名（可包含扩展名）
     * @param insertTimestampBeforeExt 是否在扩展名前插入时间后缀
     */
    public static void saveJson(Object obj, String directory, String fileName, boolean insertTimestampBeforeExt) {
        // 序列化为JSON
        String jsonContent = JSON.toJSONString(
                obj,
                JSONWriter.Feature.PrettyFormat,
                JSONWriter.Feature.WriteMapNullValue
        );
        writeStringToResource(directory, fileName, insertTimestampBeforeExt, jsonContent);
    }
    public static void saveJson(Object obj,String fullPath){
        String jsonContent = JSON.toJSONString(
                obj,
                JSONWriter.Feature.PrettyFormat,
                JSONWriter.Feature.WriteMapNullValue
        );
        FileUtil.writeUtf8String(jsonContent, fullPath);
    }

    /**
     * 保存纯文本到资源目录
     * @param text 文本内容
     * @param directory 目标子目录（如 CONFIG_DIRECTORY / RESULT_DIRECTORY）
     * @param fileName 文件名（可包含扩展名）
     * @param insertTimestampBeforeExt 是否在扩展名前插入时间后缀
     */
    public static void saveText(String text, String directory, String fileName, boolean insertTimestampBeforeExt) {
        if (text == null) {
            text = "";
        }
        if (directory == null || directory.trim().isEmpty()) {
            throw new IllegalArgumentException("目录不能为空");
        }
        if (fileName == null || fileName.trim().isEmpty()) {
            throw new IllegalArgumentException("文件名不能为空");
        }
        writeStringToResource(directory, fileName, insertTimestampBeforeExt, text);
    }

    /**
     * 将字符串内容写入资源目录（公用底层逻辑）
     */
    private static void writeStringToResource(String directory, String fileName, boolean insertTimestampBeforeExt, String content) {
        try {
            // 处理文件名：是否在扩展名前插入时间后缀
            String finalFileName = fileName;
            if (insertTimestampBeforeExt) {
                String timeSuffix = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss"));
                int dotIndex = fileName.lastIndexOf('.');
                if (dotIndex > 0 && dotIndex < fileName.length() - 1) {
                    finalFileName = fileName.substring(0, dotIndex) + "_" + timeSuffix + fileName.substring(dotIndex);
                } else {
                    finalFileName = fileName + "_" + timeSuffix;
                }
            }

            String relativePath = directory + finalFileName;
            logger.info("正在保存文件: " + relativePath);

            String resourcePath = CompareUtils.getResourceDirectoryPath();
            String normalizedRelativePath = relativePath.replace("/", File.separator);
            Path fullPath = Paths.get(resourcePath, normalizedRelativePath);

            Path parentDir = fullPath.getParent();
            if (parentDir != null && !Files.exists(parentDir)) {
                Files.createDirectories(parentDir);
                logger.info("创建目录: " + parentDir);
            }

            Files.write(fullPath, content.getBytes(StandardCharsets.UTF_8));
            logger.info("文件保存成功: " + fullPath);

        } catch (Exception e) {
            logger.severe("保存文件失败: " + e.getMessage());
            throw new RuntimeException("保存文件失败: " + e.getMessage(), e);
        }
    }
    public static String load(String path){
       return FileUtil.readUtf8String( path);
    }
    public static <T> T loadObject(String path, Class<T> clazz){
        if (path == null || clazz == null) {
            throw new IllegalArgumentException("path或clazz不能为空");
        }
        return JSON.parseObject(load(path), clazz);
    }
}
